import matplotlib.pyplot as plt
import os

class Controller:
    def __init__(self, model, view):
        self.model = model
        self.view = view
        self.view.on_load = self.load_file  # 设置视图的on_load方法
        self.view.on_show_plot = self.display_signal_plots
        self.view.on_convert = self.convert2mat

        # 设置生成报告按钮的命令
        self.view.report_button['command'] = self.generate_report
        self.view.show_plot_button['command'] = self.display_signal_plots
    def convert2mat(self,dir_path):
        if os.path.isdir(dir_path):
            self.model.export_mf4_as_mat(dir_path)


    def load_file(self, file_path):
        if file_path:
            # 调用模型的方法来处理文件
            self.model.load_mf4(file_path)
            # 之后可以更新视图或进行其他操作

    def generate_report(self):
        # 调用模型的generate_report方法来生成报告
        self.model.generate_report()

    def add_signal_figure(self, signal, default, comment):
        # 生成左边的图（更大的时间范围）
        fig_left, ax_left = self.model.plot_signal_around_key_frames(signal)
        # 生成右边的图（特定的时间范围）
        fig_right, ax_right, start_time, end_time = self.model.find_non_default_range_within_window(
            signal, default)

        if fig_left and fig_right:
            # 创建一个组合图像
            fig_combined, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9))
            fig_combined.subplots_adjust(bottom=0.25)  # 调整底部，为文本留出空间
            # 在左边的图像上重新绘制线条
            for line in ax_left.get_lines():
                ax1.plot(line.get_xdata(), line.get_ydata(), color=line.get_color())

            # 在右边的图像上重新绘制线条
            for line in ax_right.get_lines():
                ax2.plot(line.get_xdata(), line.get_ydata(), color=line.get_color())

            # ---------自定义区域-----------------------------------------------
            # 如果是纵向距离信号，则在右图添加红色的水平线以表明纵向距离不能小于4.1，超过0.5则可能有感知问题（可变范围）
            if signal == "Disp_AEBObj_PrimTarIntv_PosnLgt":
                ax2.axhline(y=4.1, color='red', linestyle='-', linewidth=2)
                ax2.axhline(y=3.6, color='red', linestyle='--', linewidth=2)
                # 在右图的右上方添加信号释意文本
            # 如果是aeb触发信号则添加驾驶员干预时刻。
            if signal == "out_ADCU_AEBWarning":
                warnings_text = "0x0: NO_WARNING\n0x1: PreWarning to car\n0x2: Latent distance Warning\n" + \
                                "0x3: Braking to car\n0x4: PreWarning to PED\n0x5: Braking to PED\n0x6-0x7: Reserved"
                ax2.text(0.95, 0.95, warnings_text, transform=ax2.transAxes, fontsize=8,
                         verticalalignment='top', horizontalalignment='right')
                
            if signal == "in_IPB_vehicleSpeed":
                if self.model.manual_intervention_time is not None:
                    ax2.axvline(x=self.model.manual_intervention_time, color='red', linestyle='--',
                            label='驾驶员介入时刻')
                    ax2.legend()
                else:
                    warnings_text = "驾驶员未介入\n"
                    ax2.text(0.95, 0.95, warnings_text, transform=ax2.transAxes, fontsize=8,
                         verticalalignment='top', horizontalalignment='right')

            # 如果是请求减速度信号，则在右图绘制出最大减速度竖线。
            if signal =="out_ADCU_AEB_DECEL_CMD":
                L = min(len(self.model.lgt_min),len(self.model.decel_min))
                if L>0:
 
                        ax2.axvline(x=self.model.lgt_min[0], color='red', linestyle='--',
                                label='纵向减速度极小值点'+str(0))
                        ax2.legend()
                        ax2.axvline(x=self.model.decel_min[0], color='blue', linestyle='--',
                                label='请求减速度极小值点'+str(0))
                        ax2.legend()
                L = min(len(self.model.lgt_max),len(self.model.decel_max))
                if L>0:
       
                        ax2.axvline(x=self.model.lgt_max[0], color='red', linestyle='-',
                                label='纵向减速度极大值点'+str(0))
                        ax2.legend()
                        ax2.axvline(x=self.model.decel_max[0], color='blue', linestyle='-',
                                label='请求减速度极大值点'+str(0))
                        ax2.legend()
            # ----------------------------------------------------------------
            # 在左边的图像上画红框，只有边框为红色
            # 假设您已经知道要框出的时间范围 start_time 和 end_time
            ax1.axvspan(start_time, end_time, edgecolor='red', facecolor='none', alpha=1, linewidth=2)

            # 设置轴标题等
            ax1.set_title(ax_left.get_title())
            ax1.set_xlabel(ax_left.get_xlabel())
            ax1.set_ylabel(ax_left.get_ylabel())

            ax2.set_title(ax_right.get_title())
            ax2.set_xlabel(ax_right.get_xlabel())
            ax2.set_ylabel(ax_right.get_ylabel())
            # 在组合图像下方添加评论
            fig_combined.text(0.5, 0.05, comment, ha='center', va='bottom', fontsize=10,
                              transform=fig_combined.transFigure)

            # 显示和保存组合图像
            self.view.show_figure(fig_combined)
            fig_combined.savefig("combined_plot.png")

    def display_signal_plots(self):
        print("按下绘图键")

        self.add_signal_figure("ADCU_AEBWarning", 0, self.model.analyze_aeb_fcw_trigger("ADCU_AEBWarning"))
        self.add_signal_figure("Disp_AEBObj_PrimTarIntv_PosnLgt", 200, self.model.analyze_posnlgt_signal())
        self.add_signal_figure("in_IPB_vehicleSpeed", 200, self.model.calculate_speed_reduction())
        self.add_signal_figure("Disp_AEBObj_PrimTarIntv_TiToCllsn", 100, self.model.TTC_Analysis())
        self.add_signal_figure("out_ADCU_AEB_DECEL_CMD", 0, self.model.IPB_Analysis())
